package com.example.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.commons.core.domain.BaseResponse;
import com.example.commons.core.vo.receive.SystemDictTypeReceiveVo;
import com.example.commons.core.vo.result.SystemDictTypeResultVo;
import com.example.system.service.SystemDictDataService;
import com.example.system.service.SystemDictTypeService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("sys/dict")
public class SystemDictController {

    private final SystemDictDataService systemDictDataService;
    private final SystemDictTypeService systemDictTypeService;

    public SystemDictController(SystemDictDataService systemDictDataService, SystemDictTypeService systemDictTypeService) {
        this.systemDictDataService = systemDictDataService;
        this.systemDictTypeService = systemDictTypeService;
    }

    @GetMapping("/getDictPage")
    public BaseResponse<IPage<SystemDictTypeResultVo>> getDictPage(SystemDictTypeReceiveVo vo) {
        IPage<SystemDictTypeResultVo> iPage = new Page<>(vo.getPageNum(), vo.getPageSize());
        return BaseResponse.ok(systemDictTypeService.getDictPage(iPage, vo));
    }

    @PostMapping("/updateOrInsert")
    @Transactional
    public BaseResponse<String> updateOrInsert(@RequestBody SystemDictTypeResultVo vo) {
        Assert.isTrue(!vo.getDictValueVoList().isEmpty(), "字典值不能为空");
        systemDictTypeService.saveOrUpdate(vo);
        vo.getDictValueVoList().forEach(data -> data.setTypeId(vo.getId()));
        systemDictDataService.saveOrUpdateBatch(vo.getDictValueVoList());
        return BaseResponse.ok();
    }

    @DeleteMapping("delDict/{dictId}")
    public BaseResponse<Boolean> delDict(@PathVariable("dictId") Long dictId) {
        return BaseResponse.ok(systemDictTypeService.removeById(dictId));
    }
}
